import java.util.*;
public class test {
    // leetcode 54.螺旋矩阵
    class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            ArrayList<Integer> list = new ArrayList<>();
            if (matrix.length == 1) {
                if(matrix[0].length == 1){
                    list.add(matrix[0][0]);
                }else{
                    for(int i = 0; i < matrix[0].length; i++){
                        list.add(matrix[0][i]);
                    }
                }
                return list;
            }
            int rows = matrix.length;
            int cols = matrix[0].length;
            // 俄罗斯套娃
            // 应该每次算出四个极点位置
            int right = matrix[0].length - 1;
            int down = matrix.length - 1;
            int left = 0;
            int up = 1;
            int x = 0;
            int y = 0;
            // 右下左上 0 1 2 3 代替  默认向右
            int direction = 0;
            while (list.size() < rows * cols) {
                // 判断极点位置
                if (direction == 0) {
                    if (y < right) {
                        list.add(matrix[x][y]);
                        y++;
                    } else {
                        list.add(matrix[x][y]);
                        direction = 1;
                        x++;
                        right--;
                    }
                } else if (direction == 1) {
                    if (x < down) {
                        list.add(matrix[x][y]);
                        x++;
                    } else {
                        list.add(matrix[x][y]);
                        direction = 2;
                        y--;
                        down--;
                    }
                } else if (direction == 2) {
                    if (y > left) {
                        list.add(matrix[x][y]);
                        y--;
                    } else {
                        list.add(matrix[x][y]);
                        direction = 3;
                        x--;
                        left++;
                    }
                } else if (direction == 3) {
                    if (x > up) {
                        list.add(matrix[x][y]);
                        x--;
                    } else {
                        list.add(matrix[x][y]);
                        direction = 0;
                        y++;
                        up++;
                    }
                }
            }

            return list;
        }
    }
}
